/*java jdk 1.7+
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''*/

package com.zxy.pay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import org.json.JSONObject;

import com.zxy.common.Com_Fun;
import com.zxy.common.Com_Para;
import com.zxy.common.MD5Util;
import com.zxy.common.Sha1Util;

public class WxPayConfig
{
	// 微信app AppSecret 获取token使用
	public String	AppSecret			= "0add9610323fea0d175a718b7770e989";															// "7ab4f0a69938f63c17803c54df7abf22";
	// API Key
	public String	srckey				= "xxxx";																						// "3941a569b4c6b82a097f01527b06ad70";//"07DE0BA1EF154c5c88E490BBBF796FF1";
	// 微信分配的公众账号ID（企业号corpid即为此appId）
	public String	appid				= "wxc1aeab60d32fb67a";																			// "wxb0a0be9239dbb03f";
	// 微信支付分配的商户号
	public String	mch_id				= "xxxx";
	// 随机字符串，不长于32位
	public String	nonce_str			= Com_Fun.Get_New_GUID().replace("-","");
	// 终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB"
	public String	device_info			= "WEB";
	// 签名，详见签名生成算法
	public String	sign				= "";
	// 签名类型，目前支持HMAC-SHA256和MD5，默认为MD5
	public String	sign_type			= "MD5";																						// MD5
	// 商品简单描述，该字段须严格按照规范传递，具体请见参数规定 应用市场上的APP名字-商品概述
	public String	body				= "xxxx";
	// 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
	public String	out_trade_no		= "";
	// 订单总金额，单位为分，
	public String	total_fee			= "1";
	// 必须传正确的用户端IP
	public String	spbill_create_ip	= "0.0.0.0";
	// 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
	public String	notify_url			= "http://xxx.xx.xxx.xxx:8888/WxPay.html";
	// H5支付的交易类型为MWEB APP
	public String	trade_type			= "APP";
	// 场景信息
	public String	scene_info			= "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":\"http://xxx.xx.xx.xx\",\"wap_name\":\"xxx\"}}";
	// 预支付交易会话ID
	public String	prepayid			= "";
	// 时间戳
	public String	timestamp			= String.valueOf(new Date().getTime()
			/ 1000);

	// 统一下单加签
	public void InitSign()
	{
		if(this.out_trade_no.length() > 32)
			this.out_trade_no = this.out_trade_no.substring(0,32);
		String stringSignTemp = "appid=" + this.appid + "&body=" + this.body
				+ "&device_info=" + this.device_info + "&mch_id=" + this.mch_id
				+ "&nonce_str=" + this.nonce_str + "&notify_url="
				+ this.notify_url + "&out_trade_no=" + this.out_trade_no
				+ "&scene_info=" + this.scene_info + "&sign_type="
				+ this.sign_type + "&spbill_create_ip=" + this.spbill_create_ip
				+ "&total_fee=" + this.total_fee + "&trade_type="
				+ this.trade_type + "&key=" + this.srckey;
		try
		{
			this.sign = MD5Util.MD5Encode(stringSignTemp,"UTF-8").toUpperCase();
		}
		catch(Exception e)
		{
		}
	}

	// 获取prepayid并加签
	public void InitSign2()
	{
		this.nonce_str = Com_Fun.Get_New_GUID().replace("-","");
		this.timestamp = String.valueOf(new Date().getTime() / 1000);
		try
		{
			List<String> signParams = new ArrayList<String>();
			signParams.add("appid=" + this.appid);
			signParams.add("noncestr=" + this.nonce_str);
			signParams.add("package=Sign=WXPay");
			signParams.add("partnerid=" + this.mch_id);
			signParams.add("prepayid=" + this.prepayid);
			signParams.add("timestamp=" + this.timestamp);
			this.sign = genAppSign(signParams);
		}
		catch(Exception e)
		{
		}
	}

	private String genAppSign(List<String> params)
	{
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i < params.size();i++)
		{
			sb.append(params.get(i).toString());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(this.srckey);
		String appSign = MD5Util.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return appSign;
	}

	// 获取支付订单
	public String getJSONOrderInfo()
	{
		InitSign2();
		return "{\"appid\":\"" + this.appid + "\"," + "\"partnerid\":\""
				+ this.mch_id + "\"," + "\"prepayid\":\"" + this.prepayid
				+ "\"," + "\"package\":\"Sign=WXPay\"," + "\"noncestr\":\""
				+ this.nonce_str + "\"," + "\"timestamp\":\"" + timestamp
				+ "\"," + "\"sign\":\"" + sign + "\"}";
	}

	// 统一下单
	public String getOrderInfoApp()
	{
		if(this.out_trade_no.length() > 32)
			this.out_trade_no = this.out_trade_no.substring(0,32);
		return "<xml>" + "<appid>" + this.appid + "</appid>" + "<body>"
				+ this.body + "</body>" + "<device_info>" + this.device_info
				+ "</device_info>" + "<mch_id>" + this.mch_id + "</mch_id>"
				+ "<nonce_str>" + this.nonce_str + "</nonce_str>"
				+ "<notify_url>" + this.notify_url + "</notify_url>"
				+ "<out_trade_no>" + this.out_trade_no + "</out_trade_no>"
				+ "<scene_info>" + this.scene_info + "</scene_info>"
				+ "<sign_type>" + this.sign_type + "</sign_type>"
				+ "<spbill_create_ip>" + this.spbill_create_ip
				+ "</spbill_create_ip>" + "<total_fee>" + this.total_fee
				+ "</total_fee>" + "<trade_type>" + this.trade_type
				+ "</trade_type>" + "<sign>" + this.sign + "</sign>" + "</xml>";
	}

	public String getOrderInfoH5()
	{
		if(this.out_trade_no.length() > 32)
			this.out_trade_no = this.out_trade_no.substring(0,32);
		return "<xml>" + "<appid>" + this.appid + "</appid>" + "<mch_id>"
				+ this.mch_id + "</mch_id>" + "<nonce_str>" + this.nonce_str
				+ "</nonce_str>" + "<device_info>" + this.device_info
				+ "</device_info>" + "<sign>" + this.sign + "</sign>"
				+ "<sign_type>" + this.sign_type + "</sign_type>" + "<body>"
				+ this.body + "</body>" + "<out_trade_no>" + this.out_trade_no
				+ "</out_trade_no>" + "<total_fee>" + this.total_fee
				+ "</total_fee>" + "<spbill_create_ip>" + this.spbill_create_ip
				+ "</spbill_create_ip>" + "<notify_url>" + this.notify_url
				+ "</notify_url>" + "<trade_type>" + this.trade_type
				+ "</trade_type>" + "<scene_info>" + this.scene_info
				+ "</scene_info>" + "</xml>";
	}

	public String SendDataServerWx_Post(String strUrl, String strPost)
	{
		OutputStream out = null;
		BufferedReader in = null;
		InputStream isr = null;
		String result = "";
		try
		{
			URL realUrl = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			conn.setRequestProperty("accept","*/*");
			conn.setRequestProperty("connection","close");// Keep-Alive
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=UTF-8");
			conn.setUseCaches(true);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(60000);
			conn.setReadTimeout(60000);
			out = conn.getOutputStream();
			out.write(strPost.getBytes("UTF-8"));
			out.flush();
			out.close();
			int resultCode = conn.getResponseCode();
			if(HttpURLConnection.HTTP_OK == resultCode)
			{
				isr = conn.getInputStream();
				byte[] Bytes = new byte[2048];
				int i = isr.read(Bytes,0,Bytes.length);
				byte[] bytem = new byte[i];
				for(int j = 0;j < i;j++)
				{
					bytem[j] = Bytes[j];
				}
				result = new String(bytem,Com_Para.U_CODE);
			}
			conn.disconnect();
		}
		catch(Exception e)
		{
		}
		finally
		{
			try
			{
				if(!java.util.Objects.equals(out,null))
				{
					out.close();
				}
				if(!java.util.Objects.equals(in,null))
				{
					in.close();
				}
				if(!java.util.Objects.equals(isr,null))
					isr.close();
			}
			catch(IOException ex)
			{
			}
		}
		return result;
	}

	public String SendDataServerWx(String strUrl)
	{
		OutputStream out = null;
		BufferedReader in = null;
		InputStream isr = null;
		String result = "";
		try
		{
			URL realUrl = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			conn.setRequestProperty("accept","*/*");
			conn.setRequestProperty("connection","close");// Keep-Alive
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=UTF-8");
			conn.setUseCaches(true);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(60000);
			conn.setReadTimeout(60000);
			out = conn.getOutputStream();
			out.flush();
			out.close();
			int resultCode = conn.getResponseCode();
			if(HttpURLConnection.HTTP_OK == resultCode)
			{
				isr = conn.getInputStream();
				byte[] Bytes = new byte[2048];
				int i = isr.read(Bytes,0,Bytes.length);
				byte[] bytem = new byte[i];
				for(int j = 0;j < i;j++)
				{
					bytem[j] = Bytes[j];
				}
				result = new String(bytem,Com_Para.U_CODE);
			}
			conn.disconnect();
		}
		catch(Exception e)
		{
		}
		finally
		{
			try
			{
				if(!java.util.Objects.equals(out,null))
				{
					out.close();
				}
				if(!java.util.Objects.equals(in,null))
				{
					in.close();
				}
				if(!java.util.Objects.equals(isr,null))
					isr.close();
			}
			catch(IOException ex)
			{
			}
		}
		return result;
	}

	// 微信获取令牌
	public StringBuilder Wx_Login(String Auth_Code)
	{
		StringBuilder strResult = new StringBuilder();
		try
		{
			String strUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+ this.appid + "&secret=" + this.AppSecret + "&code="
					+ Auth_Code + "&grant_type=authorization_code";
			strResult.append(SendDataServerWx(strUrl));
			JSONObject json = null;
			try
			{
				json = new JSONObject(strResult.toString());
				if(!java.util.Objects.equals(json,null) && !json.has("retcode"))
				{
					String accessToken = json.getString("access_token");
					String openID = json.getString("openid");
					strUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
							+ accessToken + "&openid=" + openID;
					strResult.delete(0,strResult.length());
					strResult.append(SendDataServerWx(strUrl));
					json = new JSONObject(strResult.toString());
					// Ope_DB_Go pdg = new Ope_DB_Go();
					// String session_id = Com_Fun.Get_New_GUID();
					// String INF_EN_NAME = "A01_Wx_Login_OK";
					// String nick_name = "";
					// String user_id = "";
					// String avatar = "";
					// if(json.has("openid"))
					// user_id = json.getString("openid");
					// if(json.has("headimgurl"))
					// avatar = json.getString("headimgurl");
					// if(json.has("nickname"))
					// nick_name = json.getString("nickname");
					// else nick_name = user_id;
					// String[] Parameters = {nick_name,user_id,avatar};
					// String[] ParamTypes = {"STRING","STRING","STRING"};
					// String[] ParamOutName = new String[0];
					// String[] ParamOutType = new String[0];
					// String[] ReturnName =
					// {"s_result","error_desc","login_id","nickname","ALIPAY_ACCOUNT","M_ACCOUNT","E_M_NUMBER"};
					// String[] ReturnValue = {"","","","","","",""};
					// String[] ReturnType =
					// {"INT","STRING","STRING","STRING","STRING","STRING","INT"};
					// int[] ReturnISIMG = {0,0,0,0,0,0,0};
					// strResult.delete(0,strResult.length());
					// strResult.append(pdg.Ope_DB(session_id,INF_EN_NAME,Parameters,ParamTypes,ParamOutName,ParamOutType,ReturnName,ReturnValue,ReturnType,ReturnISIMG,ReturnISIMG));
				}
			}
			catch(Exception ess)
			{
				strResult.delete(0,strResult.length());
				strResult.append("{\"A01_Wx_Login_OK\":[{\"s_result\":\"0\",\"error_desc\":\"获取微信用户信息失败："
						+ ess.getMessage() + "\"}]}");
			}
		}
		catch(Exception e)
		{
			strResult.delete(0,strResult.length());
			strResult.append("{\"A01_Wx_Login_OK\":[{\"s_result\":\"0\",\"error_desc\":\"获取微信用户信息失败："
					+ e.getMessage() + "\"}]}");
			com.zxy.adminlog.UsAdmin_Log uL = new com.zxy.adminlog.UsAdmin_Log(Com_Para.ApplicationPath,new StringBuilder("Wx_Login出错["
					+ strResult + "]\r\n"));
			try
			{
				uL.WriteLog();
			}
			catch(IOException e1)
			{
			}
		}
		return strResult;
	}

	// 微信获取令牌
	public StringBuilder Wx_Login2(String Auth_Code, String IS_SER, String IS_DEM)
	{
		StringBuilder strResult = new StringBuilder();
		try
		{
			String strUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+ this.appid + "&secret=" + this.AppSecret + "&code="
					+ Auth_Code + "&grant_type=authorization_code";
			strResult.append(SendDataServerWx(strUrl));
			JSONObject json = null;
			try
			{
				json = new JSONObject(strResult.toString());
				if(!java.util.Objects.equals(json,null) && !json.has("retcode"))
				{
					String accessToken = json.getString("access_token");
					String openID = json.getString("openid");
					strUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
							+ accessToken + "&openid=" + openID;
					strResult.delete(0,strResult.length());
					strResult.append(SendDataServerWx(strUrl));
					json = new JSONObject(strResult.toString());
					// Ope_DB_Go pdg = new Ope_DB_Go();
					// String session_id = Com_Fun.Get_New_GUID();
					// String INF_EN_NAME = "A01_Wx_Login_OK";
					// String nick_name = "";
					// String user_id = "";
					// String avatar = "";
					// if(json.has("openid"))
					// user_id = json.getString("openid");
					// if(json.has("headimgurl"))
					// avatar = json.getString("headimgurl");
					// if(json.has("nickname"))
					// nick_name = json.getString("nickname");
					// else nick_name = user_id;
					// String[] Parameters =
					// {nick_name,user_id,avatar,IS_SER,IS_DEM};
					// String[] ParamTypes =
					// {"STRING","STRING","STRING","STRING","STRING"};
					// String[] ParamOutName = new String[0];
					// String[] ParamOutType = new String[0];
					// String[] ReturnName =
					// {"s_result","error_desc","login_id","nickname","ALIPAY_ACCOUNT","M_ACCOUNT"};
					// String[] ReturnValue = {"","","","","","",""};
					// String[] ReturnType =
					// {"INT","STRING","STRING","STRING","STRING","STRING"};
					// int[] ReturnISIMG = {0,0,0,0,0,0};
					// strResult.delete(0,strResult.length());
					// strResult.append(pdg.Ope_DB(session_id,INF_EN_NAME,Parameters,ParamTypes,ParamOutName,ParamOutType,ReturnName,ReturnValue,ReturnType,ReturnISIMG,new
					// int[0]));
				}
			}
			catch(Exception ess)
			{
				strResult.delete(0,strResult.length());
				strResult.append("{\"A01_Wx_Login_OK\":[{\"s_result\":\"0\",\"error_desc\":\"获取微信用户信息失败："
						+ ess.getMessage() + "\"}]}");
			}
		}
		catch(Exception e)
		{
			strResult.delete(0,strResult.length());
			strResult.append("{\"A01_Wx_Login_OK\":[{\"s_result\":\"0\",\"error_desc\":\"获取微信用户信息失败："
					+ e.getMessage() + "\"}]}");
			com.zxy.adminlog.UsAdmin_Log uL = new com.zxy.adminlog.UsAdmin_Log(Com_Para.ApplicationPath,new StringBuilder("Wx_Login出错["
					+ strResult + "]\r\n"));
			try
			{
				uL.WriteLog();
			}
			catch(IOException e1)
			{
			}
		}
		return strResult;
	}

	// 微信公众号获取令牌
	public StringBuilder Wx_Login_GZH(Hashtable<String, String> htParam)
	{
		StringBuilder strResult = new StringBuilder();
		String token = "1qaz2wsxADMIN";
		String signature = htParam.get("signature");
		String timestamp = htParam.get("timestamp");
		String nonce = htParam.get("nonce");
		String echostr = htParam.get("echostr");

		// java.util.SortedMap<String,String> sortedMap = new
		// java.util.TreeMap<String,String>();
		// sortedMap.put("token",token);
		// sortedMap.put("timestamp",timestamp);
		// sortedMap.put("nonce",nonce);

		String strAva = "";
		try
		{
			// 字典排序
			String[] arr = new String[]
			{ token, timestamp, nonce };
			// 将token、timestamp、nonce三个参数进行字典序排序 Arrays.sort(arr);
			Com_Fun.sort(arr);
			StringBuilder content = new StringBuilder();
			for(int i = 0;i < arr.length;i++)
			{
				content.append(arr[i]);
			}
			// strAva = Sha1Util.DefSha1(content.toString());
			strAva = Sha1Util.getSha1(content.toString());
		}
		catch(Exception e)
		{
			strAva = "error";
		}

		if(signature.equals(strAva))
		{
			strResult.append(echostr);
		}else
		{
			strResult.append("false");
		}
		// 1）将token、timestamp、nonce三个参数进行字典序排序
		// 2）将三个参数字符串拼接成一个字符串进行sha1加密
		// 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信

		return strResult;
	}
}